package com.hyc.myvideo.ui.activity.my;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.acmenxd.toaster.Toaster;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hyc.myvideo.R;
import com.hyc.myvideo.data.api.constants.Constants;
import com.hyc.myvideo.data.api.model.BaseResult;
import com.hyc.myvideo.data.api.model.Code;
import com.hyc.myvideo.data.api.model.UserInfo;
import com.hyc.myvideo.ui.base.BaseFActivity;
import com.hyc.myvideo.widget.ClearEditText;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 编辑手机号
 * @author gyb
 * @version 1.0
 * @created 2017/07/13
 */
public class EditPhoneActivity extends BaseFActivity {
    /**当前手机号*/
    @BindView(R.id.t_phone_id) TextView textViewPhone;
    /**修改手机号*/
    @BindView(R.id.e_phone)ClearEditText editTextPhone;
    /**获取输入验证码*/
    @BindView(R.id.e_verification_code)ClearEditText editTextCode;
    /**点击获取验证码*/
    @BindView(R.id.b_verification_id) TextView textViewVerification;
    /**提交按钮*/
    @BindView(R.id.b_submit_id)
    Button buttonSubmit;
    private TimeCount timeCount = new TimeCount(60000, 1000);
    private  Code code = null;
    @Override
    public int getContentViewId() {
        return R.layout.activity_edit_phone;
    }

    @Override
    protected void initView() {
        setLeftBtnClick(true,getStr(R.string.huc_head_edit_phone));
        editTextPhone.addTextChangedListener(textWatcherP);
        editTextCode.addTextChangedListener(textWatcher);
        setButtonSubmit(false);
        setTextViewVerification(false,"获取验证码");
        String phone = getIntent().getStringExtra("phone");
        String StringPhone = String.format(getString(R.string.huc_hint_enter_phone),phone);
        textViewPhone.setText(StringPhone);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void oNext(String r, String method) {
        /**获取短信返回*/
        if (method.equalsIgnoreCase(Constants.API_SMS)) {
            BaseResult<Code> result = JSONObject.parseObject(r, new TypeReference<BaseResult<Code>>(){});
            if(result.isCode()){
                this.code = result.getResult();
            }
            Toaster.show(result.getMsg());
        }
        /**修改返回*/
        if (method.equalsIgnoreCase(Constants.API_USER_UPDATE_PHONE)) {
            BaseResult<UserInfo> result = JSONObject.parseObject(r, new TypeReference<BaseResult<UserInfo>>(){});
            if (result.isCode()) {
                setCallback(result);
            }
            Toaster.show(result.getMsg());
        }
    }

    @Override
    protected void oError() {

    }

    /***
     * 成功回调返回参数
     * @param result
     */
    private void setCallback(BaseResult<UserInfo> result) {
        this.finish();
        UserInfo userInfo = result.getResult();
        String phone = userInfo.getUser_phone();
        appContext.getUserInfo().setUser_phone(phone);
        setResult(Constants.RESULT_CODE_TWO, new Intent().putExtra("phone",phone));

    }

    @OnClick({R.id.b_verification_id,R.id.b_submit_id})
    public void onClicks(View view) {
        switch (view.getId()){
            /**获取验证码*/
            case R.id.b_verification_id:
                timeCount.start();//计时开始
                api.requestPhoneCode(getBEDstr(editTextPhone));
                break;
            /**确定修改手机号*/
            case R.id.b_submit_id:
                if(code.getSms_code().equalsIgnoreCase(getBEDstr(editTextCode))){
                    api.userUpdataPhone(getBEDstr(editTextPhone),getBEDstr(editTextCode));
                }else{
                    Toaster.show("验证码错误!");
                }
                break;
        }
    }

    /**
     * 定义一个倒计时的内部类
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onTick(long millisUntilFinished) {
            /**按钮不可点击*/
            long length = millisUntilFinished / 1000;
            setTextViewVerification(false,length+" S");
        }
        @Override
        public void onFinish() {
            setTextViewVerification(true,"重新发送");
        }
    }

    /***
     * 设置验证码状态值
     * @param isClickable
     * @param str
     */
    private void setTextViewVerification(boolean isClickable, String str){
        if(textViewVerification != null){
            textViewVerification.setText(str);
            textViewVerification.setClickable(isClickable);
            if(isClickable){
                textViewVerification.setBackgroundColor(setBColor(R.color.color_1));
            }else{
                textViewVerification.setBackgroundColor(setBColor(R.color.color_4));
            }
        }
    }

    /***
     * 设置提交按钮状态
     * @param isClickable
     */
    private void setButtonSubmit(boolean isClickable){
        buttonSubmit.setClickable(isClickable);
        if(isClickable){
            buttonSubmit.setBackgroundResource(R.drawable.button_shape_1);
        }else{
            buttonSubmit.setBackgroundResource(R.drawable.button_shape_0);
        }
    }

    /***
     * 监听验证码输入框
     */
    TextWatcher textWatcher = new TextWatcher() {
        @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override public void afterTextChanged(Editable s) {
            int num = s.toString().length();
            if(num >= 4 && getBEDstr(editTextPhone).length() >= 11){
                setButtonSubmit(true);
            }else {
                setButtonSubmit(false);
            }
        }
    };

    /***
     * 监听手机号输入框
     */
    TextWatcher textWatcherP = new TextWatcher() {
        @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override public void afterTextChanged(Editable s) {
            int num = s.toString().length();
            if(num >= 11 ){
                setTextViewVerification(true,"获取验证码");
                if(getBEDstr(editTextCode).length() >= 4){
                    setButtonSubmit(true);
                }
            }else {
                setTextViewVerification(false,"获取验证码");
                setButtonSubmit(false);
            }
            timeCount.cancel();//关闭
        }
    };
}
